import _ from 'underscore'
import dispatcher from 'lib/dispatcher'
import {Scope} from 'lib/scopeFactory'

import TimeStore from 'lib/stores/time-store'
import {coreApi,sortMap,propConfig,parseToTopbar2} from '../apis/core-util'
//
 Object.defineProperty(Object.prototype, 'logx', {
  value: function (name) {
    if (name) {
      console.log(name, this);
    } else {
      console.log(this);
    }
    return this;
  },
  writable: false,
  enumerable: false,
  configurable: false
});
 //

var classifyTree = [{
  key: 'measurementname'
}, {
  key: 'hostname',
  requireId: 'nameId',
  options:{
    urlName:'webviewdomain'
  }
}];
export default class MainScope extends Scope {
  constructor(){
    super();
    this.$state = {
      viewKey: location.hash === '#/jserror/' ? 'js_error_count' : 'avg_exec', // #MI-1507
      topbar:{
        loading:true
      },
      sortOptions:_.chain(propConfig).pick('avg_exec','total_exec','exec_count','js_error_count').map(function(v,k){
        return {
          key:k,
          label:v.label
        }
      }).value()
      // }).value().logx('sortOptions')
    }
    this.topbarApi = coreApi({
      limit:20,
      classify:'measurementname',
      size:1,
      urlName:'webview'
    },TimeStore.getValue,() => {
      return {
        viewKey:this.$state.viewKey
      }
    }, () => {
      return {order:sortMap[this.$state.viewKey]}
    }, () => {
      if(this.$state.viewKey === 'js_error_count'){
        return {
          urlName:'jsError'
        }
      }
    });
  }
  fetch(){
    var _this = this
    this.topbarApi.fetch().then(function(data,params){
      // debugger
      _this.$state.topbar = {
        data:parseToTopbar2(data,params,{
          classifyTree:classifyTree
        }).map((item) => {
          // debugger
          return _.extend({},item,{
            fmtVal:null,
            routeUrl:(params.viewKey==='js_error_count'?'jserror':'')+item.routeUrl
          },params.viewKey==='js_error_count'?{
            fetchChildren:function(){
              var parent = this
              var childParam = {
                classify:'jsurl',
                nameId:item.id
              }
              return coreApi(params,childParam).fetch()
              .then((innerData,innerParams) => {
                parent.children = {
                  data:parseToTopbar2(innerData,innerParams,{
                    parent:parent
                  }).map((child) => {
                    return _.extend({},child,{
                      id:child.name,
                      routeUrl:parent.routeUrl+'/jsurl/'+encodeURIComponent(child.name)
                    })
                  })
                }
              },(err) => {
                parent.children = {
                  error:err
                }
              },(innerParams) => {
                parent.children = {
                  loading:true,
                  params:innerParams
                }
              });
            }
          }:null)
        })
      }
    },function(err){
      _this.$state.topbar = {
        error:err
      }
    },function(params){
      _this.$state.topbar = {
        loading:true,
        params:params
      }
      _this.emit()
    }).always(function(){
      _this.emit()
    })
  }
  $settime(payload){
    this.fetch()
  }
  $changesort(payload){
    this.$state.viewKey = payload.key;
    if(this.$state.viewKey === 'js_error_count'){
      this.viewInstance.props.history.pushState(null, '/jserror/');
    }else{
      this.viewInstance.props.history.pushState(null, '/');
    }
    this.fetch()
  }
  $load(){
    this.fetch()
  }
}
